package top.archiesean.common.security.service;

import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import top.archiesean.admin.dto.UserInfo;
import top.archiesean.admin.feign.UserFeign;
import top.archiesean.common.core.domain.R;
import top.archiesean.common.redis.biz.RedisService;
import top.archiesean.common.redis.constant.CacheConstants;

import java.util.concurrent.TimeUnit;

/**
 * @author ArchieSean
 * @description 用户详细信息
 * @date 2024-01-11 07:40
 */
@Primary
@Slf4j
public class UserDetailsServiceImpl implements SeanUserDetailsService {


    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从缓存中获取user信息
        Object object = RedisService.getObject(CacheConstants.USER_DETAILS + username);
        if (ObjUtil.isNotEmpty(object)) {
            return (UserDetails) object;
        }
        R<UserInfo> userInfoR = userFeign.loadByUsername(username);
        UserDetails details = getUserDetails(userInfoR);
        if (ObjUtil.isNotEmpty(details)) {
            RedisService.set(CacheConstants.USER_DETAILS + username, details, 30, TimeUnit.MINUTES);
        }

        return details;
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
